package com.example;

import java.io.*;
import java.util.*;

public class TxtIntersection {

  public static void main(String[] args) {
    // 读取第一个文本文件的内容
    Set<String> set1 = readFile("/Users/xiaoxu.wu/Desktop/RAM-词库-20240808.txt");

    // 读取第二个文本文件的内容
    Set<String> set2 = readFile("/Users/xiaoxu.wu/Desktop/网上下载词库.txt");

    // 求两个集合的交集
    Set<String> intersection = new HashSet<>(set1);
    intersection.retainAll(set2);

    // 将交集写入新的文本文件
    writeToFile("/Users/xiaoxu.wu/Desktop/RAM-20240808有效词库.txt", intersection);
  }

  // 读取文本文件的内容并返回一个字符串集合
  private static Set<String> readFile(String fileName) {
    Set<String> set = new HashSet<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
      String line;
      while ((line = reader.readLine()) != null) {
        set.add(line.trim());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return set;
  }

  // 将字符串集合写入文本文件
  private static void writeToFile(String fileName, Set<String> set) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
      set.stream().sorted().forEach(str -> {
        try {
          writer.write(str);
          writer.newLine();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      });
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
